/**********************************************************************************
  Snes9x - Portable Super Nintendo Entertainment System (TM) emulator.

  (c) Copyright 1996 - 2002  Gary Henderson (gary.henderson@ntlworld.com),
                             Jerremy Koot (jkoot@snes9x.com)

  (c) Copyright 2002 - 2004  Matthew Kendora

  (c) Copyright 2002 - 2005  Peter Bortas (peter@bortas.org)

  (c) Copyright 2004 - 2005  Joel Yliluoma (http://iki.fi/bisqwit/)

  (c) Copyright 2001 - 2006  John Weidman (jweidman@slip.net)

  (c) Copyright 2002 - 2006  funkyass (funkyass@spam.shaw.ca),
                             Kris Bleakley (codeviolation@hotmail.com)

  (c) Copyright 2002 - 2007  Brad Jorsch (anomie@users.sourceforge.net),
                             Nach (n-a-c-h@users.sourceforge.net),
                             zones (kasumitokoduck@yahoo.com)

  (c) Copyright 2006 - 2007  nitsuja


  BS-X C emulator code
  (c) Copyright 2005 - 2006  Dreamer Nom,
                             zones

  C4 x86 assembler and some C emulation code
  (c) Copyright 2000 - 2003  _Demo_ (_demo_@zsnes.com),
                             Nach,
                             zsKnight (zsknight@zsnes.com)

  C4 C++ code
  (c) Copyright 2003 - 2006  Brad Jorsch,
                             Nach

  DSP-1 emulator code
  (c) Copyright 1998 - 2006  _Demo_,
                             Andreas Naive (andreasnaive@gmail.com)
                             Gary Henderson,
                             Ivar (ivar@snes9x.com),
                             John Weidman,
                             Kris Bleakley,
                             Matthew Kendora,
                             Nach,
                             neviksti (neviksti@hotmail.com)

  DSP-2 emulator code
  (c) Copyright 2003         John Weidman,
                             Kris Bleakley,
                             Lord Nightmare (lord_nightmare@users.sourceforge.net),
                             Matthew Kendora,
                             neviksti


  DSP-3 emulator code
  (c) Copyright 2003 - 2006  John Weidman,
                             Kris Bleakley,
                             Lancer,
                             z80 gaiden

  DSP-4 emulator code
  (c) Copyright 2004 - 2006  Dreamer Nom,
                             John Weidman,
                             Kris Bleakley,
                             Nach,
                             z80 gaiden

  OBC1 emulator code
  (c) Copyright 2001 - 2004  zsKnight,
                             pagefault (pagefault@zsnes.com),
                             Kris Bleakley,
                             Ported from x86 assembler to C by sanmaiwashi

  SPC7110 and RTC C++ emulator code
  (c) Copyright 2002         Matthew Kendora with research by
                             zsKnight,
                             John Weidman,
                             Dark Force

  S-DD1 C emulator code
  (c) Copyright 2003         Brad Jorsch with research by
                             Andreas Naive,
                             John Weidman

  S-RTC C emulator code
  (c) Copyright 2001-2006    byuu,
                             John Weidman

  ST010 C++ emulator code
  (c) Copyright 2003         Feather,
                             John Weidman,
                             Kris Bleakley,
                             Matthew Kendora

  Super FX x86 assembler emulator code
  (c) Copyright 1998 - 2003  _Demo_,
                             pagefault,
                             zsKnight,

  Super FX C emulator code
  (c) Copyright 1997 - 1999  Ivar,
                             Gary Henderson,
                             John Weidman

  Sound DSP emulator code is derived from SNEeSe and OpenSPC:
  (c) Copyright 1998 - 2003  Brad Martin
  (c) Copyright 1998 - 2006  Charles Bilyue'

  SH assembler code partly based on x86 assembler code
  (c) Copyright 2002 - 2004  Marcus Comstedt (marcus@mc.pp.se)

  2xSaI filter
  (c) Copyright 1999 - 2001  Derek Liauw Kie Fa

  HQ2x, HQ3x, HQ4x filters
  (c) Copyright 2003         Maxim Stepin (maxim@hiend3d.com)

  Win32 GUI code
  (c) Copyright 2003 - 2006  blip,
                             funkyass,
                             Matthew Kendora,
                             Nach,
                             nitsuja

  Mac OS GUI code
  (c) Copyright 1998 - 2001  John Stiles
  (c) Copyright 2001 - 2007  zones


  Specific ports contains the works of other authors. See headers in
  individual files.


  Snes9x homepage: http://www.snes9x.com

  Permission to use, copy, modify and/or distribute Snes9x in both binary
  and source form, for non-commercial purposes, is hereby granted without
  fee, providing that this license information and copyright notice appear
  with all copies and any derived work.

  This software is provided 'as-is', without any express or implied
  warranty. In no event shall the authors be held liable for any damages
  arising from the use of this software or it's derivatives.

  Snes9x is freeware for PERSONAL USE only. Commercial users should
  seek permission of the copyright holders first. Commercial use includes,
  but is not limited to, charging money for Snes9x or software derived from
  Snes9x, including Snes9x or derivatives in commercial game bundles, and/or
  using Snes9x as a promotion for your commercial product.

  The copyright holders request that bug fixes and improvements to the code
  should be forwarded to them so everyone can benefit from the modifications
  in future versions.

  Super NES and Super Nintendo Entertainment System are trademarks of
  Nintendo Co., Limited and its subsidiary companies.
**********************************************************************************/

/**********************************************************************************
  Snes9x GTK Port
  
  (c) Copyright 2007 - 2008  Brandon Wright (bearoso@gmail.com)
**********************************************************************************/

#include <stdio.h>
#include <sys/time.h>
#include <gdk/gdk.h>
#include <gdk/gdkx.h>

#include "gtk_s9x.h"
#include "gtk_control.h"
#include "gtk_sound.h"
#include "gtk_display.h"

#define IDLE_FUNC_PRIORITY (G_PRIORITY_DEFAULT_IDLE)

void S9xPostRomInit (void);
void S9xSyncSpeedFinish (void);
gboolean S9xIdleFunc (gpointer data);

Snes9xConfig *gui_config;
Snes9xWindow *top_level;
static struct timeval next_frame_time = { 0, 0 };
static struct timeval now;
int syncing;
guint idle_func_id;

int
main (int argc,
      char *argv[])
{   
    g_thread_init (NULL);
    gdk_threads_init ();
    
    gtk_init (&argc, &argv);
    glade_init ();
#ifdef USE_OPENGL
    gtk_gl_init (&argc, &argv);
#endif
          
    ZeroMemory (&Settings, sizeof (Settings));
        
    /* Allow original config file for backend settings */
    S9xLoadConfigFiles (argv, argc); 
    
    /* Perform our config here */
    gui_config = new Snes9xConfig ();
    
    S9xInitInputDevices ();
    
    gui_config->load_config_file ();
    
    top_level = new Snes9xWindow (gui_config);
    top_level->show ();
    
    char *rom_filename = S9xParseArgs (argv, argc);
    
    S9xReportControllers ();
    
    if (!Memory.Init () || !S9xInitAPU ())
        exit (3);
    
    Memory.PostRomInitFunc = S9xPostRomInit;
    
    S9xPortSoundInit ();    
        
    S9xInitDisplay (argc, argv);
    
    gui_config->reconfigure ();
    top_level->update_accels ();
    
    Settings.Paused = TRUE;
    syncing = 0;
    idle_func_id = g_idle_add_full (IDLE_FUNC_PRIORITY,
                                    S9xIdleFunc, 
                                    NULL,
                                    NULL);
    
    if (rom_filename)
    {
        if (S9xOpenROM (rom_filename))
            S9xNoROMLoaded ();
    }
    else
    {
        S9xNoROMLoaded ();
    }
        
    gtk_main ();
    
    return 0;
}

int
S9xOpenROM (const char *rom_filename)
{
    /* FIXME: oldstyle loading */
    
    if (gui_config->rom_loaded)
    {
        S9xAutoSaveSRAM ();
    }
    
    uint32 flags = CPU.Flags;  
     
    bool8 loaded = FALSE;

    if (Settings.Multi)
        loaded = Memory.LoadMultiCart (Settings.CartAName, Settings.CartBName);
    else if (rom_filename)
        loaded = Memory.LoadROM (rom_filename);
    
    Settings.StopEmulation = !loaded;

    if (!loaded && rom_filename)
    {
        char dir [_MAX_DIR + 1];
        char drive [_MAX_DRIVE + 1];
        char name [_MAX_FNAME + 1];
        char ext [_MAX_EXT + 1];
        char fname [_MAX_PATH + 1];
         
        _splitpath (rom_filename, drive, dir, name, ext);
        _makepath (fname, drive, dir, name, ext);

        strcpy (fname, S9xGetDirectory (ROM_DIR));
        strcat (fname, SLASH_STR);
        strcat (fname, name);
         
        if (ext [0])
        {
            strcat (fname, ".");
            strcat (fname, ext);
        }
         
        _splitpath (fname, drive, dir, name, ext);
        _makepath (fname, drive, dir, name, ext);
         
        if ((Settings.StopEmulation = !Memory.LoadROM (fname)))
        {
            fprintf (stderr, "Error opening: %s\n", rom_filename);

            return -1;
        }
         
        loaded = TRUE;
    }
   
    if (loaded)
    {   
        Memory.LoadSRAM (S9xGetFilename (".srm", SRAM_DIR));
        S9xLoadCheatFile (S9xGetFilename (".cht", PATCH_DIR));
    }
    else
    {
        S9xReset ();
        Settings.Paused |= 2;
    }  
     
    CPU.Flags = flags;
 
    S9xROMLoaded ();
    
    return 0;
}

void
S9xROMLoaded (void)
{
    gui_config->rom_loaded = TRUE;
    top_level->set_rom_loaded_state ();
    
    S9xSoundStart ();
    
    return;
}

void
S9xNoROMLoaded (void)
{
    S9xSoundStop ();
    gui_config->rom_loaded = FALSE;
    top_level->set_no_rom_loaded_state ();
    
    return;
}

gboolean
S9xSleepFunc (gpointer data)
{
    idle_func_id = g_idle_add_full (IDLE_FUNC_PRIORITY,
                                    S9xIdleFunc, 
                                    NULL,
                                    NULL);
    
    return FALSE;
}

gboolean
S9xPauseFunc (gpointer data)
{
    if (!gui_config->rom_loaded)
        return TRUE;
    
    if (!Settings.Paused) /* Coming out of pause */
    {   
#ifdef USE_JOYSTICK
        /* Clear joystick queues */
        gui_config->flush_joysticks ();
#endif
        
        S9xSetSoundMute (FALSE);
        S9xSoundStart ();
        
        /* Resume high-performance callback */
        idle_func_id = g_idle_add_full (IDLE_FUNC_PRIORITY,
                                        S9xIdleFunc, 
                                        NULL,
                                        NULL);
        top_level->update_statusbar ();
        return FALSE;
    }
    
    return TRUE;
}

gboolean 
S9xIdleFunc (gpointer data)
{       
    if (Settings.Paused)
    {
        S9xSetSoundMute (TRUE);
        S9xSoundStop ();
        
#ifdef USE_JOYSTICK
        gui_config->flush_joysticks ();
#endif

        /* Move to a timer-based function to use less CPU */
        g_timeout_add (100, S9xPauseFunc, NULL);
        top_level->update_statusbar ();
        return FALSE;
    }
    
    if (syncing)
        S9xSyncSpeedFinish ();
        
    S9xProcessEvents (TRUE);
    
    S9xMainLoop ();
    
    return TRUE;
}

/* Snes9x core hooks */
void 
S9xMessage (int type, int number, const char *message)
{
    /*
    fprintf (stderr, "%s\n", message);
     */
    return;
}

/* Varies from ParseArgs because this one is for the OS port to handle */
void 
S9xParseArg (char **argv, int &i, int argc)
{
    return;
}

/* Finishes syncing by using more accurate system sleep functions*/
void
S9xSyncSpeedFinish (void)
{
    if (!syncing)
        return;
    
    gettimeofday (&now, NULL);
    
    while (timercmp (&next_frame_time, &now, >))
    {
        unsigned time_left = (next_frame_time.tv_sec  - now.tv_sec) * 1000000 +
                              next_frame_time.tv_usec - now.tv_usec;
        
        usleep (time_left);
        
        gettimeofday (&now, NULL);
    }
    
    next_frame_time.tv_usec += Settings.FrameTime;
    
    if (next_frame_time.tv_usec >= 1000000)
    {
        next_frame_time.tv_sec += next_frame_time.tv_usec / 1000000;
        next_frame_time.tv_usec %= 1000000;
    }
    
    syncing = 0;
    
    return;
}

/* SyncSpeed Handles delays between frames, similar to unix.cpp version, 
 * cleaned up for clarity, adjusted for GUI event loop */
void
S9xSyncSpeed (void)
{
    unsigned int limit;
    int lag;
    
    if (Settings.HighSpeedSeek > 0)
    {
        Settings.HighSpeedSeek--;
        IPPU.RenderThisFrame = FALSE;
        IPPU.SkippedFrames = 0;
        
        gettimeofday (&now, NULL);
        next_frame_time = now;
        
        syncing = 0;
        
        return;
    }
    
    else if (Settings.TurboMode)
    {   
        if ((++IPPU.FrameSkip >= Settings.TurboSkipFrames || Settings.OldTurbo)
            && !Settings.HighSpeedSeek)
        {
            IPPU.FrameSkip = 0;
            IPPU.SkippedFrames = 0;
            IPPU.RenderThisFrame = TRUE;
        }       
        else
        {
            IPPU.SkippedFrames++;
            IPPU.RenderThisFrame = FALSE;
        }
        
        return;
    } 
    
    gettimeofday (&now, NULL);
    
    if (next_frame_time.tv_sec == 0)
    {
        next_frame_time = now; 
        ++next_frame_time.tv_usec;
    }
    
    if (Settings.SkipFrames == AUTO_FRAMERATE)
    {
        lag = (now.tv_sec  - next_frame_time.tv_sec) * 1000000 +
               now.tv_usec - next_frame_time.tv_usec;

        /* We overcompensate the frame time by a frame in case it's just a CPU 
         * discrepancy. We can recover lost time in the next frame anyway. */
        if (lag > (int) (Settings.FrameTime)) 
        {
            IPPU.RenderThisFrame = 0;
            IPPU.SkippedFrames++;
        }
        else
        {
            IPPU.RenderThisFrame = 1;
            IPPU.SkippedFrames = 0;
        }
    }
    else
    {   
        limit = Settings.SkipFrames + 1;
                
        IPPU.SkippedFrames++;
        IPPU.RenderThisFrame = 0;
                        
        if (IPPU.SkippedFrames >= limit)
        {
            IPPU.RenderThisFrame = 1;
            IPPU.SkippedFrames = 0;
        }
    }
        
    if (timercmp (&next_frame_time, &now, <))
    {
        lag = (now.tv_sec  - next_frame_time.tv_sec) * 1000000 +
        now.tv_usec - next_frame_time.tv_usec;

        if (lag >= 500000)
        {
            next_frame_time = now;
        }
    }
        
    syncing = 1; 
    
    return;
}

/* Final exit point, issues exit (0) */
void
S9xExit (void)
{
    S9xPortSoundDeinit ();
        
    Settings.StopEmulation = TRUE;
    if (gui_config->rom_loaded)
        S9xAutoSaveSRAM ();
    
    if(Settings.SPC7110)
        (*CleanUp7110) ();
    
    S9xDeinitAPU (); 
  /*  Memory.Deinit (); */ /* Segfaults */    
    
    gui_config->save_config_file ();
    
    S9xDeinitInputDevices ();
    S9xDeinitDisplay ();
    
    gtk_main_quit ();
    return;
} 

void 
S9xPostRomInit (void)
{
    //First plug in both, they'll change later as needed
    S9xSetController (0, CTL_JOYPAD,     0, 0, 0, 0);
    S9xSetController (1, CTL_JOYPAD,     1, 0, 0, 0);
    top_level->set_menu_item_selected ("joypad1");
    top_level->set_menu_item_selected ("joypad2");
    
    if (!strncmp ((const char *) Memory.NSRTHeader + 24, "NSRT", 4))
    {
        switch (Memory.NSRTHeader[29])
        {
            case 0: //Everything goes
                break;

            case 0x10: //Mouse in Port 0
                S9xSetController (0, CTL_MOUSE,      0, 0, 0, 0);
                top_level->set_menu_item_selected ("mouse1");                     
                break;

            case 0x01: //Mouse in Port 1
                S9xSetController (1, CTL_MOUSE,      1, 0, 0, 0);
                top_level->set_menu_item_selected ("mouse2");
                break;

            case 0x03: //Super Scope in Port 1
                S9xSetController (1, CTL_SUPERSCOPE, 0, 0, 0, 0);
                top_level->set_menu_item_selected ("superscope1");
                break;

            case 0x06: //Multitap in Port 1
                S9xSetController (1, CTL_MP5,        1, 2, 3, 4);
                top_level->set_menu_item_selected ("multitap1");
                break;

            case 0x66: //Multitap in Ports 0 and 1
                S9xSetController (0, CTL_MP5,        0, 1, 2, 3);
                S9xSetController (1, CTL_MP5,        4, 5, 6, 7);
                top_level->set_menu_item_selected ("multitap1");
                top_level->set_menu_item_selected ("multitap2");
                break;

            case 0x08: //Multitap in Port 1, Mouse in new Port 1
                S9xSetController (1, CTL_MOUSE,      1, 0, 0, 0);
                //There should be a toggle here for putting in Multitap instead
                top_level->set_menu_item_selected ("mouse2");
                break;

            case 0x04: //Pad or Super Scope in Port 1
                S9xSetController (1, CTL_SUPERSCOPE, 0, 0, 0, 0);
                top_level->set_menu_item_selected ("superscope2");
                //There should be a toggle here for putting in a pad instead
                break;

            case 0x05: //Justifier - Must ask user...
                S9xSetController (1, CTL_JUSTIFIER,  1, 0, 0, 0);
                //There should be a toggle here for how many justifiers
                break;

            case 0x20: //Pad or Mouse in Port 0
                S9xSetController (0, CTL_MOUSE,      0, 0, 0, 0);
                //There should be a toggle here for putting in a pad instead
                break;

            case 0x22: //Pad or Mouse in Port 0 & 1
                S9xSetController (0, CTL_MOUSE,      0, 0, 0, 0);
                S9xSetController (1, CTL_MOUSE,      1, 0, 0, 0);
                //There should be a toggles here for putting in pads instead
                break;

            case 0x24: //Pad or Mouse in Port 0, Pad or Super Scope in Port 1
                //There should be a toggles here for what to put in, I'm leaving it at gamepad for now
                break;

            case 0x27: //Pad or Mouse in Port 0, Pad or Mouse or Super Scope in Port 1
                //There should be a toggles here for what to put in, I'm leaving it at gamepad for now
                break;

                //Not Supported yet
            case 0x99: break; //Lasabirdie
            case 0x0A: break; //Barcode Battler
        }
    }
    
    return;
}

const char *
S9xStringInput(const char *message)
{
    return NULL;
}

void 
S9xExtraUsage (void)
{
    return;
}
